package org.moonlight.jvm.cmd;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import lombok.Data;

import java.util.List;

/**
 * 命令行参数解析对象
 * @author Moonlight
 * @createTime 2023/8/14 13:46
 **/
@Data
@Parameters(separators = "=")
public class Cmd {
    @Parameter(names = {"-inst", "-verbose:inst"}, description = "输出字节码指令信息", order = 5)
    private boolean verboseInst;
    @Parameter(names = {"-verbose", "-verbose:class"}, description = "输出类加载信息", order = 4)
    private boolean verboseClass;
    @Parameter(names = {"-?", "-help"}, description = "输出帮助信息", order = 3, help = true)
    private boolean help = false;
    @Parameter(names = "-version", description = "输出版本信息", order = 2)
    private boolean version = false;
    @Parameter(names = {"-cp", "-classpath"}, description = "设置类路径", order = 1)
    private String classpath;
    @Parameter(description = "启动类和启动参数")
    private List<String> mainClassAndArgs;
    @Parameter(names = {"-Xjre"}, description = "jre目录路径,用于寻找和加载Java标准库(jre/lib)及扩展库(jre/lib/ext)中的类.非标准参数.", order = 4)
    private String jre;

    /** 通过命令行传进来的原始参数 **/
    private String[] args;

    /** 启动类 **/
    private String mainClass;
    /** 启动参数 **/
    private List<String> appArgs;
    /** 是否解析成功 **/
    private boolean ok;

    public static Cmd parse(String[] argv) {
        Cmd args = new Cmd();
        JCommander cmd = JCommander.newBuilder().addObject(args).build();
        cmd.parse(argv);
        args.setOk(true);
        args.setArgs(argv);

        List<String> mainClassAndArgs = args.getMainClassAndArgs();

        args.setMainClass(mainClassAndArgs.get(0));

        if (mainClassAndArgs.size() > 1) {
            args.setAppArgs(mainClassAndArgs.subList(1, mainClassAndArgs.size()));
        }

        return args;
    }
}